package org.example.work1.order.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.work1.order.entity.Account;
import org.example.work1.order.entity.Order;
import org.example.work1.order.redis.RedisCache;
import org.example.work1.order.service.AccountService;
import org.example.work1.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 帐户控制器
 *
 * @author xh
 * @date 2023/03/08
 */
@RestController
@Slf4j
@RequestMapping(value = "/v1")
public class OrderController {

    @Autowired
    private RedisCache redisCache;

    @Autowired(required = false)
    private AccountService accountService;

    @Autowired(required = false)
    private OrderService orderService;

    @PostMapping(value = "/order")
    public void addOrder(Order order) {

        String key = order.getPayerId();
       //1.从redis获取缓存信息 ，考虑是否引入布隆过滤器
       Account account = redisCache.get(key);
       if(account == null){
           //2.从数据库获取信息（库初始化的时候同步account信息，消息队列用于后面新增或更新账户信息）
           account = accountService.getById(order.getPayerId());

       }

        if(account != null){
            //更新redis key
            redisCache.set(key, account);
        }else{
            //判断或统计是否高频,设置空对象
            redisCache.set(key, new Account());
        }

       if(account.getMoney() < order.getPrice()){
           //校验不通过
           log.error("客户余额不足！");
       }else{
           //产生订单、入库
           orderService.save(order);
       }
    }


}
